﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LogicalComponent.rules.grid;
using System.Text.RegularExpressions;

namespace TestLogicalComponent.rules.grid
{
    class MapReader : TileFactory<TileLogic>
    {
        List<List<TileLogic>> tileGrid;
        public int Width { get { return this.tileGrid[0].Count; } }
        public int Length { get { return this.tileGrid.Count; } }

        public MapReader(string file) {
            Regex valueMatcher = new Regex(@"^\s*(\S+)");
           
            this.tileGrid = new List<List<TileLogic>>();
            
            foreach (string line in File.ReadLines(file))
            {
                int start = 0; 
                List<TileLogic> tileRow = new List<TileLogic>();
                
                while (valueMatcher.IsMatch(line.Substring(start))) 
                {

                    Match m = valueMatcher.Match(line.Substring(start));
                    start += m.Length;
                    string value = m.Groups[1].Value;
                    if (!StartsWithDigit(value))
                    {
                        tileRow.Add(this.GetTileFromCode(value));
                    }
                }

                if (tileRow.Count > 0){
                    this.tileGrid.Add(tileRow);
                }
            }
        }

        private bool StartsWithDigit(string s)
        {
            return Regex.IsMatch(s, @"^\d");
        }
        
        public override TileLogic MakeTile(int x, int z) {
            return this.tileGrid[z][x];
        }

        private TileLogic GetTileFromCode(string code)
        {
            TileLogic t = new TileLogic();
            switch (code)
            {
                case ("A"):
                    // Mountain
                    t.MoveModType = MoveCostModType.MULTIPLIER;
                    t.MoveModValue = 3;
                    break;
                case ("~"):
                    // Water
                    t.MoveModType = MoveCostModType.IMPASSABLE;
                    break;
                case ("@"):
                    // Forest
                    t.MoveModType = MoveCostModType.ADDER;
                    t.MoveModValue = 1;
                    break;
                case ("_"):
                    // Plains
                    t.MoveModType = MoveCostModType.ADDER;
                    t.MoveModValue = 0;
                    break;
                default:
                    throw new Exception("Unrecognized code '" + code + "'");
            }
            return t;
        }

        
    }
}
